import Vue from 'vue'
import ElementUI from 'element-ui'
import VueRouter from 'vue-router'
import login from '@/views/login.vue'
import index from '@/views/index.vue'
import receiveOrder from '@/views/receiveOrder/receiveOrder'
import receiveReport from '@/views/receiveReport/receiveReport'
// 解决路由重复点击报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    redirect: '/login',
    meta: { requireAuth: false, title: '登录' }
  },
  {
    path: '/login',
    name: 'login',
    component: login,
    meta: { requireAuth: false, title: '登录' }
  },
  {
    path: '/index',
    name: 'index',
    component: index,
    redirect: '/index/receiveOrder',
    children: [
      { path: 'receiveOrder', component: receiveOrder, meta: { requireAuth: true, title: '领取订单' } },
      { path: 'receiveReport', component: receiveReport, meta: { requireAuth: true, title: '领取报表' } }
    ]
  }
]

const router = new VueRouter({
  routes
})
/* 路由守卫配置 */
router.beforeEach((to, from, next) => {
  const token = window.sessionStorage.getItem('token')
  // const token = true
  if (to.meta.requireAuth) {
    if (!token) {
      ElementUI.Message({
        message: '请先登录',
        type: 'error'
      })
      router.push('/')
    } else {
      next()
    }
  } else {
    // 登录 不用验证直接放行
    next()
  }
})
/* 配置title */
// router.afterEach((to, form) => {
//   document.title = to.meta.title
// })
export default router
